import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  Steps,
  Timeline,
  Tabs,
  Drawer,
  Avatar,
  Progress,
  Descriptions,
  Empty
} from 'antd'
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  HistoryOutlined,
  ReloadOutlined,
  SearchOutlined,
  UserOutlined,
  ClockCircleOutlined,
  SendOutlined,
  FileTextOutlined,
  SettingOutlined,
  DashboardOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  StopOutlined,
  RollbackOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { ApprovalProcess, ApprovalHistory, ApprovalQuery, ApprovalStats, PageResult } from '@/types/index'

const { Search } = Input
const { TextArea } = Input
const { TabPane } = Tabs

interface ApprovalManagementProps {}

const ApprovalManagement: React.FC<ApprovalManagementProps> = () => {
  // 状态管理
  const [tableLoading, setTableLoading] = useState(false)
  const [processes, setProcesses] = useState<ApprovalProcess[]>([])
  const [stats, setStats] = useState<ApprovalStats>()
  const [processDefinitions, setProcessDefinitions] = useState<any[]>([])
  
  // 分页和查询
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`
  })
  
  const [query, setQuery] = useState<ApprovalQuery>({
    current: 1,
    size: 10
  })
  
  // 弹窗和抽屉状态
  const [approvalModalVisible, setApprovalModalVisible] = useState(false)
  const [startModalVisible, setStartModalVisible] = useState(false)
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false)
  const [historyDrawerVisible, setHistoryDrawerVisible] = useState(false)
  
  // 选中状态
  const [selectedProcess, setSelectedProcess] = useState<ApprovalProcess>()
  const [processHistory, setProcessHistory] = useState<ApprovalHistory[]>([])
  const [activeTab, setActiveTab] = useState('all')
  
  // 表单实例
  const [approvalForm] = Form.useForm()
  const [startForm] = Form.useForm()

  // 业务类型选项
  const businessTypeOptions = [
    { label: '组件审批', value: 'COMPONENT_APPROVAL' },
    { label: '主题场景审批', value: 'THEME_SCENARIO_APPROVAL' },
    { label: '模板审批', value: 'TEMPLATE_APPROVAL' },
    { label: '用户权限审批', value: 'USER_PERMISSION_APPROVAL' },
    { label: '数据访问审批', value: 'DATA_ACCESS_APPROVAL' },
    { label: '自定义审批', value: 'CUSTOM_APPROVAL' }
  ]

  // 状态选项
  const statusOptions = [
    { label: '草稿', value: 'DRAFT' },
    { label: '已提交', value: 'SUBMITTED' },
    { label: '审批中', value: 'IN_PROGRESS' },
    { label: '已通过', value: 'APPROVED' },
    { label: '已拒绝', value: 'REJECTED' },
    { label: '已取消', value: 'CANCELLED' },
    { label: '已超时', value: 'TIMEOUT' },
    { label: '异常', value: 'ERROR' }
  ]

  // 优先级选项
  const priorityOptions = [
    { label: '低', value: 'LOW' },
    { label: '普通', value: 'NORMAL' },
    { label: '高', value: 'HIGH' },
    { label: '紧急', value: 'URGENT' }
  ]

  // 获取审批流程列表
  const fetchProcesses = async (params: ApprovalQuery = query) => {
    setTableLoading(true)
    try {
      const response = await fetch('/api/approval/page', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(params)
      })
      
      if (response.ok) {
        const result: PageResult<ApprovalProcess> = await response.json()
        setProcesses(result.records)
        setPagination(prev => ({
          ...prev,
          current: result.current,
          total: result.total
        }))
      } else {
        message.error('获取审批流程列表失败')
      }
    } catch (error) {
      console.error('获取审批流程列表失败:', error)
      message.error('网络错误，请重试')
    } finally {
      setTableLoading(false)
    }
  }

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await fetch('/api/approval/statistics?userId=current_user')
      if (response.ok) {
        const result = await response.json()
        setStats(result)
      }
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 获取流程定义列表
  const fetchProcessDefinitions = async () => {
    try {
      const response = await fetch('/api/approval/process-definitions')
      if (response.ok) {
        const result = await response.json()
        setProcessDefinitions(result)
      }
    } catch (error) {
      console.error('获取流程定义列表失败:', error)
    }
  }

  // 刷新数据
  const refreshData = () => {
    fetchProcesses()
    fetchStats()
    fetchProcessDefinitions()
  }

  // 初始化
  useEffect(() => {
    refreshData()
  }, [])

  // 表格列定义
  const columns: ColumnsType<ApprovalProcess> = [
    {
      title: '流程名称',
      dataIndex: 'processDefinitionName',
      key: 'processDefinitionName',
      width: 200,
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 500 }}>{text}</span>
          <span style={{ fontSize: '12px', color: '#666' }}>{record.businessObjectName}</span>
        </Space>
      )
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      width: 120,
      render: (type) => {
        const typeMap = {
          COMPONENT_APPROVAL: { color: 'blue', text: '组件审批' },
          THEME_SCENARIO_APPROVAL: { color: 'green', text: '场景审批' },
          TEMPLATE_APPROVAL: { color: 'orange', text: '模板审批' },
          USER_PERMISSION_APPROVAL: { color: 'purple', text: '权限审批' },
          DATA_ACCESS_APPROVAL: { color: 'cyan', text: '数据审批' },
          CUSTOM_APPROVAL: { color: 'default', text: '自定义' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config?.color}>{config?.text}</Tag>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusMap = {
          DRAFT: { color: 'default', text: '草稿', icon: <FileTextOutlined /> },
          SUBMITTED: { color: 'processing', text: '已提交', icon: <SendOutlined /> },
          IN_PROGRESS: { color: 'processing', text: '审批中', icon: <ClockCircleOutlined /> },
          APPROVED: { color: 'success', text: '已通过', icon: <CheckCircleOutlined /> },
          REJECTED: { color: 'error', text: '已拒绝', icon: <CloseOutlined /> },
          CANCELLED: { color: 'default', text: '已取消', icon: <StopOutlined /> },
          TIMEOUT: { color: 'warning', text: '已超时', icon: <ExclamationCircleOutlined /> },
          ERROR: { color: 'error', text: '异常', icon: <ExclamationCircleOutlined /> }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return (
          <Tag color={config?.color} icon={config?.icon}>
            {config?.text}
          </Tag>
        )
      }
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 80,
      render: (priority) => {
        const priorityMap = {
          LOW: { color: 'default', text: '低' },
          NORMAL: { color: 'processing', text: '普通' },
          HIGH: { color: 'warning', text: '高' },
          URGENT: { color: 'error', text: '紧急' }
        }
        const config = priorityMap[priority as keyof typeof priorityMap]
        return <Tag color={config?.color}>{config?.text}</Tag>
      }
    },
    {
      title: '进度',
      key: 'progress',
      width: 120,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <Progress 
            percent={Math.round((record.currentStep / record.totalSteps) * 100)}
            size="small"
            showInfo={false}
          />
          <span style={{ fontSize: '12px', color: '#666' }}>
            {record.currentStep}/{record.totalSteps}
          </span>
        </Space>
      )
    },
    {
      title: '当前审批人',
      dataIndex: 'currentApproverName',
      key: 'currentApproverName',
      width: 120,
      render: (name) => name ? (
        <Space>
          <Avatar size="small" icon={<UserOutlined />} />
          {name}
        </Space>
      ) : '-'
    },
    {
      title: '提交人',
      key: 'submitter',
      width: 120,
      render: (_, record) => (
        <Space>
          <Avatar size="small" icon={<UserOutlined />} />
          {record.submitterName}
        </Space>
      )
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
      width: 150,
      render: (time) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space wrap>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="流程历史">
            <Button
              type="text"
              icon={<HistoryOutlined />}
              onClick={() => handleViewHistory(record)}
            />
          </Tooltip>
          {record.status === 'IN_PROGRESS' && record.currentApprover === 'current_user' && (
            <Tooltip title="审批">
              <Button
                type="text"
                icon={<CheckOutlined />}
                onClick={() => handleApproval(record)}
              />
            </Tooltip>
          )}
          {(record.status === 'DRAFT' || record.status === 'SUBMITTED') && record.submitter === 'current_user' && (
            <Tooltip title="撤回">
              <Button
                type="text"
                icon={<RollbackOutlined />}
                onClick={() => handleWithdraw(record)}
              />
            </Tooltip>
          )}
          <Tooltip title="同步状态">
            <Button
              type="text"
              icon={<ReloadOutlined />}
              onClick={() => handleSync(record)}
            />
          </Tooltip>
        </Space>
      )
    }
  ]

  // 事件处理函数
  const handleSearch = (keyword: string) => {
    const newQuery = { ...query, keyword, current: 1 }
    setQuery(newQuery)
    fetchProcesses(newQuery)
  }

  const handleTabChange = (key: string) => {
    setActiveTab(key)
    let newQuery = { ...query, current: 1 }
    
    switch (key) {
      case 'pending':
        newQuery.currentApprover = 'current_user'
        newQuery.status = 'IN_PROGRESS'
        break
      case 'completed':
        // 需要从历史记录中查询
        break
      case 'started':
        newQuery.submitter = 'current_user'
        break
      default:
        delete newQuery.currentApprover
        delete newQuery.status
        delete newQuery.submitter
    }
    
    setQuery(newQuery)
    fetchProcesses(newQuery)
  }

  const handleTableChange = (page: any) => {
    const newQuery = {
      ...query,
      current: page.current,
      size: page.pageSize
    }
    setQuery(newQuery)
    fetchProcesses(newQuery)
  }

  const handleStartProcess = () => {
    setStartModalVisible(true)
  }

  const handleStartSubmit = async () => {
    try {
      const values = await startForm.validateFields()
      const response = await fetch('/api/approval/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values)
      })
      
      if (response.ok) {
        message.success('流程启动成功')
        setStartModalVisible(false)
        startForm.resetFields()
        fetchProcesses()
      } else {
        message.error('流程启动失败')
      }
    } catch (error) {
      console.error('流程启动失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleApproval = (record: ApprovalProcess) => {
    setSelectedProcess(record)
    setApprovalModalVisible(true)
  }

  const handleApprovalSubmit = async () => {
    try {
      const values = await approvalForm.validateFields()
      const response = await fetch('/api/approval/complete-task', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          externalTaskId: selectedProcess?.externalProcessId,
          operator: 'current_user',
          ...values
        })
      })
      
      if (response.ok) {
        message.success('审批完成')
        setApprovalModalVisible(false)
        approvalForm.resetFields()
        fetchProcesses()
      } else {
        message.error('审批失败')
      }
    } catch (error) {
      console.error('审批失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleViewDetails = (record: ApprovalProcess) => {
    setSelectedProcess(record)
    setDetailDrawerVisible(true)
  }

  const handleViewHistory = async (record: ApprovalProcess) => {
    setSelectedProcess(record)
    
    try {
      const response = await fetch(`/api/approval/${record.id}/history`)
      if (response.ok) {
        const history = await response.json()
        setProcessHistory(history)
        setHistoryDrawerVisible(true)
      } else {
        message.error('获取流程历史失败')
      }
    } catch (error) {
      console.error('获取流程历史失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleWithdraw = async (record: ApprovalProcess) => {
    try {
      const response = await fetch(`/api/approval/${record.id}/withdraw`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          operator: 'current_user',
          comment: '申请人撤回'
        })
      })
      
      if (response.ok) {
        message.success('撤回成功')
        fetchProcesses()
      } else {
        message.error('撤回失败')
      }
    } catch (error) {
      console.error('撤回失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleSync = async (record: ApprovalProcess) => {
    try {
      const response = await fetch(`/api/approval/${record.id}/sync`, {
        method: 'POST'
      })
      
      if (response.ok) {
        message.success('同步成功')
        fetchProcesses()
      } else {
        message.error('同步失败')
      }
    } catch (error) {
      console.error('同步失败:', error)
      message.error('网络错误，请重试')
    }
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      {stats && (
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总流程数"
                value={stats.totalProcesses}
                prefix={<DashboardOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="待办任务"
                value={stats.myPendingTasks}
                prefix={<ClockCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="已办任务"
                value={stats.myCompletedTasks}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="我发起的"
                value={stats.myStartedProcesses}
                prefix={<SendOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="超时流程"
                value={stats.timeoutProcesses}
                prefix={<ExclamationCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均耗时"
                value={stats.averageProcessTime}
                suffix="小时"
                precision={1}
                prefix={<ClockCircleOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 主要内容区域 */}
      <Card>
        {/* 顶部操作栏 */}
        <div style={{ marginBottom: '16px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <Search
                  placeholder="搜索流程名称、业务对象"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={handleSearch}
                />
              </Space>
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleStartProcess}
                >
                  发起流程
                </Button>
                <Button
                  icon={<SettingOutlined />}
                >
                  流程配置
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={refreshData}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 类型筛选标签 */}
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="全部流程" key="all" />
          <TabPane tab="我的待办" key="pending" />
          <TabPane tab="我的已办" key="completed" />
          <TabPane tab="我发起的" key="started" />
        </Tabs>

        {/* 流程列表表格 */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={processes}
          loading={tableLoading}
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => handleTableChange({ current: page, pageSize })
          }}
          scroll={{ x: 1400 }}
          size="middle"
        />
      </Card>

      {/* 发起流程模态框 */}
      <Modal
        title="发起流程"
        open={startModalVisible}
        onOk={handleStartSubmit}
        onCancel={() => setStartModalVisible(false)}
        width={600}
      >
        <Form
          form={startForm}
          layout="vertical"
        >
          <Form.Item
            name="processDefinitionKey"
            label="流程类型"
            rules={[{ required: true, message: '请选择流程类型' }]}
          >
            <Select placeholder="请选择流程类型">
              {processDefinitions.map(def => (
                <Select.Option key={def.key} value={def.key}>
                  {def.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="businessType"
            label="业务类型"
            rules={[{ required: true, message: '请选择业务类型' }]}
          >
            <Select placeholder="请选择业务类型">
              {businessTypeOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="businessObjectId"
            label="业务对象ID"
            rules={[{ required: true, message: '请输入业务对象ID' }]}
          >
            <Input placeholder="请输入业务对象ID" />
          </Form.Item>
          <Form.Item
            name="businessObjectName"
            label="业务对象名称"
            rules={[{ required: true, message: '请输入业务对象名称' }]}
          >
            <Input placeholder="请输入业务对象名称" />
          </Form.Item>
          <Form.Item
            name="priority"
            label="优先级"
            initialValue="NORMAL"
          >
            <Select>
              {priorityOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={4} placeholder="请输入流程描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 审批模态框 */}
      <Modal
        title="流程审批"
        open={approvalModalVisible}
        onOk={handleApprovalSubmit}
        onCancel={() => setApprovalModalVisible(false)}
        width={600}
      >
        <Form
          form={approvalForm}
          layout="vertical"
        >
          <Form.Item
            name="approved"
            label="审批结果"
            rules={[{ required: true, message: '请选择审批结果' }]}
          >
            <Select placeholder="请选择审批结果">
              <Select.Option value={true}>通过</Select.Option>
              <Select.Option value={false}>拒绝</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="comment"
            label="审批意见"
            rules={[{ required: true, message: '请输入审批意见' }]}
          >
            <TextArea rows={4} placeholder="请输入审批意见" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 流程详情抽屉 */}
      <Drawer
        title="流程详情"
        placement="right"
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
        width={600}
      >
        {selectedProcess && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="流程名称">
              {selectedProcess.processDefinitionName}
            </Descriptions.Item>
            <Descriptions.Item label="业务类型">
              {businessTypeOptions.find(o => o.value === selectedProcess.businessType)?.label}
            </Descriptions.Item>
            <Descriptions.Item label="业务对象">
              {selectedProcess.businessObjectName}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {statusOptions.find(o => o.value === selectedProcess.status)?.label}
            </Descriptions.Item>
            <Descriptions.Item label="优先级">
              {priorityOptions.find(o => o.value === selectedProcess.priority)?.label}
            </Descriptions.Item>
            <Descriptions.Item label="当前步骤">
              {selectedProcess.currentStep} / {selectedProcess.totalSteps}
            </Descriptions.Item>
            <Descriptions.Item label="当前审批人">
              {selectedProcess.currentApproverName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="提交人">
              {selectedProcess.submitterName}
            </Descriptions.Item>
            <Descriptions.Item label="提交时间">
              {new Date(selectedProcess.submitTime).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="描述">
              {selectedProcess.approvalComment || '-'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>

      {/* 流程历史抽屉 */}
      <Drawer
        title="流程历史"
        placement="right"
        open={historyDrawerVisible}
        onClose={() => setHistoryDrawerVisible(false)}
        width={600}
      >
        {processHistory.length > 0 ? (
          <Timeline>
            {processHistory.map((item, index) => (
              <Timeline.Item
                key={index}
                color={item.result === 'SUCCESS' ? 'green' : item.result === 'FAILED' ? 'red' : 'blue'}
                dot={item.result === 'SUCCESS' ? <CheckCircleOutlined /> : item.result === 'FAILED' ? <CloseOutlined /> : <ClockCircleOutlined />}
              >
                <div>
                  <div style={{ fontWeight: 500 }}>{item.nodeName}</div>
                  <div style={{ color: '#666', fontSize: '12px', marginTop: '4px' }}>
                    审批人: {item.operatorName} | 时间: {new Date(item.operateTime || item.createTime).toLocaleString()}
                  </div>
                  {item.comment && (
                    <div style={{ marginTop: '8px', padding: '8px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                      {item.comment}
                    </div>
                  )}
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        ) : (
          <Empty description="暂无历史记录" />
        )}
      </Drawer>
    </div>
  )
}

export default ApprovalManagement